<template>
  <div class="did-h">
    <el-card class="box-card">
      <div class="separator">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/EquipList' }" style="margin-top: 5%;">用户列表</el-breadcrumb-item>
               <el-button type="primary" icon="el-icon-user-solid" size="small" @click="showAddRoleDialog = true" style="margin-top: 5%;">授予角色</el-button>
        </el-breadcrumb>
      </div>
    </el-card>

    <div class="table">
      <el-table :data="tableData" ref="multipleTable" :row-class-name="tableRowClassName" tooltip-effect="dark" style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }" @selection-change="handleSelectionChange">
        <el-table-column prop="id" label="角色ID" width="350" align="center"></el-table-column>
        <el-table-column prop="name" label="角色名" width="350" align="center"></el-table-column>
        <el-table-column prop="description" label="成员DID角色描述" width="300" align="center"></el-table-column>
        <el-table-column prop="operate" label="角色操作" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-user-solid" size="small" @click="deletePerson(scope.row)">撤销角色</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="10"
        @current-change="sizeChange"
        style="width: 50%; margin: auto; margin-top: 50px !important; display: flex; align-items: center; justify-content: center"
      ></el-pagination>
    </div>

    <el-dialog title="授予角色" :visible.sync="showAddRoleDialog" width="30%">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="角色ID">
          <el-input :disabled="true" v-model="createForm.id"></el-input>
        </el-form-item>
        <el-form-item label="角色名">
          <el-cascader :options="cascaderOptions" :props="cascaderProps" clearable @change="handleCascaderChange"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddRole">取消</el-button>
        <el-button type="primary" @click="confirmAddRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RightsManagementVue from './RightsManagement.vue';
export default {
  data() {
    return {
      input3: '',
      tableData: [],
      total: 0,
      showAddRoleDialog: false,
      createForm: {
        id: '',
        name: '',
        description: '',
        roles: '',
      },
      scope: {},
      //级联选择器（权限）
      cascaderOptions: [],
      cascaderProps: {
        multiple: true,
        value: 'name',
        label: 'name',
      },
    };
  },
  created() {
    const did = this.$route.query.id;
    const number = this.$route.query.num;
    this.createForm.id = number;
    console.log(did, number);
    this.createForm.did = did;
    this.createForm.number = number;
    this.RoleManagement();
    //获取权限列表
    this.getRoleList();
  },
  mounted() {
    this.RoleManagement('', '', '', 1); // 默认加载时搜索关键字为空字符串
  },
  computed: {
    filteredTableData() {
      if (this.input3.trim() === '') {
        return this.tableData;
      } else {
        const keyword = this.input3.trim().toLowerCase();
        return this.tableData.filter((item) => {
          return item.id.toLowerCase().includes(keyword) || item.name.toLowerCase().includes(keyword) || item.description.toLowerCase().includes(keyword);
        });
      }
    },
  },
  methods: {
    async RoleManagement(did, number, name, page) {
      let formData = new FormData();
      formData.append('did', this.createForm.did);
      formData.append('number', this.createForm.number);
      formData.append('page', page);
      formData.append('pageSize', 10);
      try {
        let res = await this.$http.post(this.$api.userIdentity.RoleManagement, formData);
        this.tableData = res;
        this.total = res.length;
      } catch (error) {
        console.error(error);
      }
    },
    //获取当前权限列表
    async getRoleList() {
      let formData = new FormData();
      formData.append('pageNum', 1);
      formData.append('pageSize', 1000);
      let res = await this.$http.post(this.$api.userIdentity.getRoleList, formData); //接口
      console.info(res);
      this.cascaderOptions = res.data.records;
    },
    //获取级联选择器的数值 选择的权限
    handleCascaderChange(selectedValues) {
      this.createForm.roles = selectedValues;
      console.log('Selected values:', selectedValues);
      console.log('this.createForm.name:', this.createForm.roles);
    },

    handleSearch() {
      // 将搜索关键字赋值给searchQuery
      const searchQuery = this.input3.trim();
      // 调用RoleManagement 方法进行搜索
      this.RoleManagement(searchQuery, '', '', 1);
    },
    handleSelectionChange() {
      // 处理表格选中项变化的逻辑
    },
    tableRowClassName() {
      // 设置表格行样式的逻辑
    },
    sizeChange(e) {
      this.RoleManagement(this.input3.trim(), '', '', e); // 传递搜索关键字和新的页码
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    cancelAddRole() {
      this.showAddRoleDialog = false;
      this.createForm = {
        id: '',
        name: '',
        description: '',
        roles: '',
      };
    },
    confirmAddRole() {
      const newRole = {
        userNumber: this.createForm.id,
        rolesName: this.createForm.roles.flat(), //角色名
        operationStatus: 0,
      };

      console.info(newRole);

      // 发送表单数据到后端
      this.$http
        .post(this.$api.userIdentity.confirmAddRole, newRole)
        .then((response) => {
          // 处理后端返回的数据
          if (response.code === 200) {
            this.tableData.push(newRole);
            this.showAddRoleDialog = false;
            this.RoleManagement();
          } else {
            console.error('Add role failed:', response.message);
          }
        })
        .catch((error) => {
          console.error('Add role error:', error);
        });
    },
    deletePerson(row) {
      const index = this.tableData.indexOf(row);

      if (index !== -1) {
        const deletedPerson = this.tableData.splice(index, 1)[0];
        deletedPerson.number = this.createForm.number;

        console.info(deletedPerson);
        const newRole = {
          userNumber: this.createForm.number,
          //角色名
          rolesName: [row.name],
          operationStatus: 1,
        };

        // 发送删除请求到后端
        this.$http
          .post(this.$api.userIdentity.deletePerson, newRole) //删除接口
          .then((response) => {
            // 处理后端返回的数据
            console.log('Delete person response:', response.data);
            this.RoleManagement(this.input3.trim(), '', '', this.$refs.multipleTable.currentPage);
          })
          .catch((error) => {
            console.error('Delete person error:', error);
          });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.did-content {
  margin-top: 10%;

  h1 {
    color: #666666;
    width: 320px;
    margin: 0 auto;
  }
}

.did-button {
  width: 100px;
  margin: 0 auto;
  margin-top: 20px;
}

.black-h {
  height: 50%;
}

.separator {
  width: 100px;
}
</style>
